package cn.bgs.controller;

import cn.bgs.pojo.EmployeeRegister;
import cn.bgs.pojo.StudentInformation;
import cn.bgs.service.LoginService;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;
    Logger log = LogManager.getLogger();

    @RequestMapping("/loginJsp")
    public String loginJsp() {
        return "login";
    }

    @RequestMapping("/registerHtml")
    public String classroomJsp() {
        return "register";
    }

    @RequestMapping("/student")
    public String student(Model m) {
        List<StudentInformation> studentInformations = loginService.findAllStudent();
        m.addAttribute("list",studentInformations);
        return "list";
    }

    @RequestMapping("/teaLogin")//登录
    public String teaLogin(Model m, String email, String password, HttpSession session) {

        EmployeeRegister register = loginService.login(email, password);

        if (register != null) {
            session.setAttribute("re", register);
            m.addAttribute("list", register);
            return "index";
        }
        session.setAttribute("error", "邮箱或密码错误");
        return "login";
    }

    @RequestMapping("/stuLogin")//登录
    public String stuLogin(Model m, String email, String password, HttpSession session) {

        StudentInformation studentInformation = loginService.stuLogin(email, password);
        RestTemplate restTemplate = new RestTemplate();
        String apiURL ="http://aider.meizu.com/app/weather/listWeather?cityIds=101010100";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(apiURL, String.class);
        m.addAttribute("list",forEntity);
        System.out.println(forEntity);
        if (studentInformation != null) {

            session.setAttribute("re", studentInformation);
            session.setAttribute("stuId", String.valueOf(studentInformation.getStuId()));

            m.addAttribute("stu", studentInformation);
            return "index";
        }
        session.setAttribute("error", "邮箱或密码错误");
        return "login";
    }

    @RequestMapping("/loginHtml")
    public String loginHtml(HttpSession session) {
        session.removeAttribute("re");
        return "login";
    }
}
